<template>
  <div class="register-page">
    <!-- <Header /> -->
    <div class="register-overlay">
      <div class="register-container">
        <div class="register-header">
          <h2>用户注册</h2>
          <el-button type="text" class="close-btn" @click="$router.push('/')">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="80px" class="register-form" @keydown.enter="handleRegister" @keydown.esc="$router.push('/')">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入用户名" size="large">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password size="large" @input="checkPasswordStrength">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
            <div class="password-strength" v-if="registerForm.password">
              <div class="strength-bar">
                <div class="strength-fill" :class="passwordStrength.level"></div>
              </div>
              <span class="strength-text" :class="passwordStrength.level">{{ passwordStrength.text }}</span>
            </div>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password size="large">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <div class="captcha-row">
              <el-input v-model="registerForm.captcha" placeholder="请输入验证码" style="width: 140px;" size="large" />
              <span class="captcha-img" @click="generateCaptcha">{{ captcha }}</span>
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="registerForm.agreeTerms" class="terms-checkbox">
              我已阅读并同意
              <el-button type="text" class="terms-link" @click="showTerms">《用户协议》</el-button>
              和
              <el-button type="text" class="terms-link" @click="showPrivacy">《隐私政策》</el-button>
            </el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button class="btn-primary" type="primary" @click="handleRegister" style="width: 100%;" :disabled="!registerForm.agreeTerms">注册</el-button>
          </el-form-item>
          <el-form-item class="register-links">
            <el-button type="text" @click="$router.push('/login')">已有账号？去登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'Register',
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        captcha: '',
        agreeTerms: false
      },
      captcha: '',
      passwordStrength: {
        level: 'weak',
        text: '密码强度：弱'
      },
      registerRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value !== this.registerForm.password) {
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            }, trigger: 'blur' }
        ],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.generateCaptcha()
  },
  methods: {
    generateCaptcha() {
      this.captcha = Math.random().toString().slice(2, 6)
    },
    checkPasswordStrength() {
      const password = this.registerForm.password
      if (!password) {
        this.passwordStrength = { level: 'weak', text: '密码强度：弱' }
        return
      }
      
      let score = 0
      if (password.length >= 8) score++
      if (/[a-z]/.test(password)) score++
      if (/[A-Z]/.test(password)) score++
      if (/[0-9]/.test(password)) score++
      if (/[^A-Za-z0-9]/.test(password)) score++
      
      if (score <= 2) {
        this.passwordStrength = { level: 'weak', text: '密码强度：弱' }
      } else if (score <= 3) {
        this.passwordStrength = { level: 'medium', text: '密码强度：中等' }
      } else {
        this.passwordStrength = { level: 'strong', text: '密码强度：强' }
      }
    },
    showTerms() {
      ElMessage.info('用户协议功能开发中...')
    },
    showPrivacy() {
      ElMessage.info('隐私政策功能开发中...')
    },
    handleRegister() {
      this.$refs.registerFormRef.validate((valid) => {
        if (!valid) return
        if (this.registerForm.captcha !== this.captcha) {
          ElMessage.error('验证码错误')
          this.generateCaptcha()
          return
        }
        if (!this.registerForm.agreeTerms) {
          ElMessage.error('请先同意用户协议和隐私政策')
          return
        }
        
        // 调用后端注册API
        this.$axios.post('/user/register', {
          account: this.registerForm.username,
          password: this.registerForm.password,
          username: this.registerForm.username
        }).then(response => {
          if (response.data.code === 1) {
            ElMessage.success('注册成功，请登录')
            this.$router.push('/login')
          } else {
            ElMessage.error(response.data.msg || '注册失败')
            this.generateCaptcha()
          }
        }).catch(error => {
          console.error('注册失败:', error)
          ElMessage.error('注册失败，请稍后重试')
          this.generateCaptcha()
        })
      })
    }
  }
}
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: var(--color-bg);
}

.register-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.register-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.15);
  min-width: 400px;
  max-width: 450px;
  animation: slideIn 0.3s ease-out;
}

@media (max-width: 768px) {
  .register-container {
    min-width: 320px;
    max-width: 90vw;
    margin: 0 1rem;
  }
  
  .register-form {
    padding: 1.5rem;
  }
  
  .register-header {
    padding: 1rem 1.5rem 0 1.5rem;
  }
  
  .register-header h2 {
    font-size: 1.3rem;
  }
}

@media (max-width: 480px) {
  .register-container {
    min-width: 280px;
    max-width: 95vw;
  }
  
  .register-form {
    padding: 1rem;
  }
  
  .register-header {
    padding: 0.8rem 1rem 0 1rem;
  }
  
  .register-header h2 {
    font-size: 1.2rem;
  }
  
  .captcha-row {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .captcha-img {
    align-self: flex-start;
  }
}

.register-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 2rem 0 2rem;
  border-bottom: 1px solid #f0f0f0;
}

.register-header h2 {
  margin: 0;
  color: var(--color-primary);
  font-size: 1.5rem;
}

.close-btn {
  color: #999;
  font-size: 1.2rem;
}

.close-btn:hover {
  color: var(--color-primary);
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.register-form {
  padding: 2rem;
}

.register-links {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
}

.btn-primary {
  height: 42px;
  font-size: 16px;
  letter-spacing: 1px;
  background: linear-gradient(90deg, #145A32 0%, #218c5c 100%);
  border: none;
}
.captcha-row {
  display: flex;
  align-items: center;
  gap: 1rem;
}
.captcha-img {
  display: inline-block;
  background: #f5f5f5;
  color: #333;
  font-weight: bold;
  font-size: 1.2rem;
  padding: 0.5rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  user-select: none;
  border: 1px solid #dcdfe6;
  transition: background 0.2s;
}
.captcha-img:hover {
  background: #e0e7ff;
}

.password-strength {
  margin-top: 0.5rem;
}

.strength-bar {
  width: 100%;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 0.25rem;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  width: 33%;
  background: #ff4757;
}

.strength-fill.medium {
  width: 66%;
  background: #ffa502;
}

.strength-fill.strong {
  width: 100%;
  background: #2ed573;
}

.strength-text {
  font-size: 0.8rem;
  font-weight: 500;
}

.strength-text.weak {
  color: #ff4757;
}

.strength-text.medium {
  color: #ffa502;
}

.strength-text.strong {
  color: #2ed573;
}

.terms-checkbox {
  font-size: 0.9rem;
  line-height: 1.4;
}

.terms-link {
  color: var(--color-primary);
  font-weight: 500;
  padding: 0;
  margin: 0;
  text-decoration: underline;
}

.terms-link:hover {
  color: #218c5c;
}

@media (max-width: 480px) {
  .terms-checkbox {
    font-size: 0.8rem;
  }
  
  .password-strength {
    margin-top: 0.25rem;
  }
  
  .strength-text {
    font-size: 0.75rem;
  }
}
</style>
